package com.app.newiptv.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.newiptv.R;
import com.app.newiptv.adaper.HomePageBottomAdapter;
import com.app.newiptv.adaper.HomePageMiddleAdapter;
import com.app.newiptv.base.MyApplication;
import com.app.newiptv.bean.HomePageBean;
import com.app.newiptv.callback.SetFocusCallBack;
import com.app.newiptv.presenter.HomePagePresenter;
import com.app.newiptv.utils.APPLog;
import com.app.newiptv.utils.Paths;
import com.app.newiptv.utils.SendMacIp;
import com.app.newiptv.utils.SystemTimeDate;
import com.app.newiptv.view.ScrollTextView;
import com.bumptech.glide.Glide;

import static com.app.newiptv.utils.Paths.BASEPATH;

public class HomePageActivity extends Activity implements HomePagePresenter.Callback, SetFocusCallBack {
    private RecyclerView middle_recycle;
    private RecyclerView bottom_recycle;
    private HomePagePresenter homePagePresenter;
    private int LOAD_COMPLETE = 1;
    private int SYSTEM_TIME = 2;
    private int NOTIC_MAR = 3;
    private int SEND_STETA = 4;
    private ImageView searcher_icon;
    private ImageView recent_see;
    private ImageView my_collect;
    private ImageView focusView;
    private ImageView imag_bg;
    private HomePageBean homePageBean;
    private ScrollTextView test_happy_view;
    private TextView system_time;
    private RelativeLayout first_layout;
    private RelativeLayout second_layout;
    private RelativeLayout third_layout;
    private ImageView logo_image;
    private Button offButton;
    private RelativeLayout programLayout;
    private TextView textView;
    private SharedPreferences sharedPreferences;
    private SharedPreferences channelPreferences;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == LOAD_COMPLETE) {
                HomePagePresenter presenter = (HomePagePresenter) msg.obj;
                int count1 = msg.arg1;
                int count2 = msg.arg2;
                onBindData(presenter, count1, count2);
            } else if (msg.what == SYSTEM_TIME) {
                handler.sendEmptyMessageDelayed(SYSTEM_TIME, 20 * 1000);
                system_time.setTypeface(MyApplication.face);
                SystemTimeDate.getSystemTime(system_time);
//                system_time.setText(SystemTimeDate.stampToDate(System.currentTimeMillis()) + "    " + SystemTimeDate.stampToHHmmDate(String.valueOf(System.currentTimeMillis())));
            } else if (msg.what == NOTIC_MAR) {
                test_happy_view.setVisibility(View.INVISIBLE);
            }
            //else if(msg.what == SEND_STETA){
            //    SendMacIp.loadData(Paths.AUTH+Paths.STATE,Contast.useName);
            //    browingSendMacIp();
            //}
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page);
        initView();
        initData();
    }
    private void browingSendMacIp(){
        handler.sendEmptyMessageDelayed(SEND_STETA,3*60*1000);
    }
    private void initData() {
        sharedPreferences = getSharedPreferences("control", 0);
        channelPreferences = getSharedPreferences("channel", 0);
        String isOff = sharedPreferences.getString("state", "off");
        programLayout.setVisibility(View.GONE);
        homePagePresenter = new HomePagePresenter(this);
        homePagePresenter.setLayout(programLayout);
        homePagePresenter.setTextView(textView);
        homePagePresenter.setSharedPreferences(channelPreferences);
        if (isOff.equals("on")) {
            offButton.setBackgroundResource(R.mipmap.liveon);
            homePagePresenter.setIsPlayLive(true);
        } else {
            offButton.setBackgroundResource(R.mipmap.liveoff);
            homePagePresenter.setIsPlayLive(false);
        }
        homePagePresenter.setDisplayed(true);
        homePagePresenter.loadLiveList();
        homePagePresenter.loadData(this);
        homePagePresenter.loadHomeNotic();
        first_layout.setOnFocusChangeListener(new SetOnFocus());
        second_layout.setOnFocusChangeListener(new SetOnFocus());
        third_layout.setOnFocusChangeListener(new SetOnFocus());
        first_layout.setOnKeyListener(new SetOnKey());
        second_layout.setOnKeyListener(new SetOnKey());
        third_layout.setOnKeyListener(new SetOnKey());
        first_layout.setOnClickListener(new SetOnClick());
        second_layout.setOnClickListener(new SetOnClick());
        third_layout.setOnClickListener(new SetOnClick());
        first_layout.requestFocus();
        middle_recycle.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    middle_recycle.post(new Runnable() {
                        @Override
                        public void run() {
                            if (middle_recycle.getChildCount() > 0) {
                                middle_recycle.getChildAt(0).requestFocus();
                            }
                        }
                    });
                }
            }
        });
        handler.sendEmptyMessageDelayed(SYSTEM_TIME, 0);
        offButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String isOff = sharedPreferences.getString("state", "off");
                if (isOff.equals("off")) {
                    editInfo("state", "on");
                    offButton.animate().scaleX(1.15f);
                    offButton.animate().scaleY(1.15f);
                    offButton.setBackgroundResource(R.mipmap.liveon);
                } else {
                    editInfo("state", "off");
                    offButton.animate().scaleX(1.0f);
                    offButton.animate().scaleY(1.0f);
                    offButton.setBackgroundResource(R.mipmap.liveoff);
                }
            }
        });
        homePagePresenter.loadData(this);
        //handler.sendEmptyMessage(SEND_STETA);
    }

    private void initView() {
        middle_recycle = (RecyclerView) this.findViewById(R.id.middle_recycle);
        bottom_recycle = (RecyclerView) this.findViewById(R.id.recycle_icon);
        searcher_icon = (ImageView) this.findViewById(R.id.search_icon);
        recent_see = (ImageView) this.findViewById(R.id.recent_see);
        my_collect = (ImageView) this.findViewById(R.id.my_collect);
        imag_bg = (ImageView) findViewById(R.id.imag_bg);
        logo_image = (ImageView) findViewById(R.id.logo_image);
        first_layout = (RelativeLayout) findViewById(R.id.fist_layout);
        second_layout = (RelativeLayout) findViewById(R.id.recent_layout);
        third_layout = (RelativeLayout) findViewById(R.id.third_layout);
        test_happy_view = (ScrollTextView) findViewById(R.id.s_tv);
        programLayout = (RelativeLayout) findViewById(R.id.program_layout);
        textView = (TextView) findViewById(R.id.text);
        offButton = (Button) findViewById(R.id.off_button);
        test_happy_view.startScroll();
        system_time = (TextView) findViewById(R.id.system_time);
        focusView = (ImageView) findViewById(R.id.focus_view);
        test_happy_view.setTypeface(MyApplication.face);
    }

    private void onBindData(HomePagePresenter presenter, int count1, int count2) {
        HomePageMiddleAdapter homePageMiddleAdapter = new HomePageMiddleAdapter(presenter, focusView, this, this);
        homePageMiddleAdapter.setCount(count1);
        HomePageBottomAdapter homePageBottomAdapter = new HomePageBottomAdapter(presenter, this, focusView);
        homePageBottomAdapter.setCount(count2);
        LinearLayoutManager manager1 = new LinearLayoutManager(HomePageActivity.this);
        manager1.setOrientation(LinearLayoutManager.HORIZONTAL);
        middle_recycle.setLayoutManager(manager1);
        LinearLayoutManager manager = new LinearLayoutManager(HomePageActivity.this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        middle_recycle.setAdapter(homePageMiddleAdapter);
        bottom_recycle.setLayoutManager(manager);
        bottom_recycle.setAdapter(homePageBottomAdapter);
    }

    @Override
    public void onError(int code, String msg) {

    }

    @Override
    public void onHomePageCompleted(HomePagePresenter presenter, int count1, HomePageBean dto) {
//        Message msg = Message.obtain();
//        msg.arg1 = count1;
//        msg.arg2 = count2;
//        msg.what = LOAD_COMPLETE;
//        msg.obj = presenter;
//        handler.sendMessage(msg);
        if (dto != null) {
            homePageBean = dto;
            onBindData(presenter, dto.getHots().size(), dto.getMenus().size());
            Glide.with(this).load(BASEPATH + dto.getBackground()).into(imag_bg);
            Glide.with(this).load(BASEPATH + dto.getLogo()).into(logo_image);
            APPLog.printInfo("logo==>:" + dto.getLogo());
        }
    }

    @Override
    public void onNoticCompleted(HomePagePresenter presenter) {
        if (Contast.HOME_MARQUEE != null) {
            test_happy_view.setVisibility(View.VISIBLE);
            test_happy_view.setText(Contast.HOME_MARQUEE);
            handler.sendEmptyMessageDelayed(NOTIC_MAR, 2 * 60 * 1000);
        }
    }

    @Override
    public void setViewFocusAble() {
        first_layout.setFocusable(true);
        second_layout.setFocusable(true);
        third_layout.setFocusable(true);
        first_layout.requestFocus();
    }


    public class SetOnFocus implements View.OnFocusChangeListener {

        @Override
        public void onFocusChange(View view, boolean b) {
            if (b) {
                //FocusedViewUtils.setFocusedView(focusView,view,10,10,10,10);
                //Toast.makeText(HomePageActivity.this, "获取到焦点", Toast.LENGTH_SHORT).show();
                view.bringToFront();
                view.setBackgroundResource(R.mipmap.bg_pic_s);
                view.animate().scaleX(1.1f);
                view.animate().scaleY(1.1f);
            } else {
                //FocusedViewUtils.setBlurView(focusView,view);
                view.setBackgroundResource(0);
                view.animate().scaleX(1.0f);
                view.animate().scaleY(1.0f);
            }
        }
    }

    public class SetOnKey implements View.OnKeyListener {

        @Override
        public boolean onKey(View view, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && event.getAction() == KeyEvent.ACTION_DOWN) {
                middle_recycle.requestFocus();
                first_layout.setFocusable(false);
                second_layout.setFocusable(false);
                third_layout.setFocusable(false);
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_BACK) {
                return true;
            }
            return false;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public class SetOnClick implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            if (view.getId() == R.id.fist_layout) {
                Intent intent = new Intent(HomePageActivity.this, SearchActivity.class);
                startActivity(intent);
            } else if (view.getId() == R.id.recent_layout) {
                Intent intent = new Intent(HomePageActivity.this, LatelyActivity.class);
                startActivity(intent);
            } else if (view.getId() == R.id.third_layout) {
                Intent intent = new Intent(HomePageActivity.this, LatelyActivity.class);
                startActivity(intent);
            }
        }
    }

    private void editInfo(String key, String info) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, info);
        editor.commit();
    }
}
